import React, { memo,useEffect,useState,useRef,useCallback } from 'react'
import { Slider } from 'antd';
import { NavLink  } from "react-router-dom";
import { useDispatch,useSelector ,shallowEqual} from "react-redux";

import { getSizeImage ,formatDate,getPlaySong} from "@/utils/format-utils";
import { getSongDetailAction ,sequenceAction,changeCurrentSong} from "../store/actionCreator";
import { PlaybarWrapper ,Control,PlayInfo,Operator} from "./style";

export default memo(function HjAppPlayBar() {
  // state
  const [isPlaying, setIsPlaying] = useState(false);
  const [isChanging, setIsChanging] = useState(false);//设一个变量，对progress做一个逻辑判断
  const [currentTime, setCurrentTime] = useState(0); //记录当前歌曲播放时间，单位为ms
  const [progress, setProgress] = useState(0); //进度条的value值 一共是100

  // redux hook
  const dispatch = useDispatch()
  const {currentSong,sequence} = useSelector(state =>({
    currentSong:state.getIn(['player','currentSong']),
    sequence:state.getIn(['player','sequence']),
  }),shallowEqual)

  // other hook
  useEffect(() => {
   dispatch(getSongDetailAction(191084))
  }, [dispatch]);

   useEffect(() => {//当页面挂载上后，才设置audioRef的src
   audioRef.current.src = getPlaySong(currentSong.id)
  //  audioRef.current.play()//刚开始一上来不能调play() 是audio标签默认的规则
   audioRef.current.play().then((res)=>{
      setIsPlaying(true)
   }).catch((err)=>{
      setIsPlaying(false)
   })
  }, [currentSong]);

  const audioRef = useRef()

  //  other handle
     const picUrl = (currentSong.al && currentSong.al.picUrl) || ""; //a.b.XXX  b undefiend 报错
     const singerName = (currentSong.ar && currentSong.ar[0].name) || "未知歌手";
     const songName = (currentSong && currentSong.name) || "未知歌名";
     const duration = (currentSong && currentSong.dt) || 0; //歌曲总时长
     const showDuration = formatDate(duration,'mm:ss')
     const showCurrentTime = formatDate(currentTime,'mm:ss')
    

     const playMusic = useCallback( () => {
       isPlaying?audioRef.current.pause():audioRef.current.play()  //点击后是否播放/暂停音频    
       setIsPlaying(!isPlaying) //取反
     },[isPlaying])
    //  audio标签监听 实时监听歌曲时间流动
     const timeUpdate = e => {
       console.log('timeUpdate执行');
       const currentTime = e.target.currentTime*1000
       const progress = (currentTime/duration) *100 //设置进度条value值
       if(!isChanging){
         setProgress(progress)
         setCurrentTime(currentTime) //化成单位为ms
       }
     }

    //  dispatch改变播放顺序
    const changeSequence = ()=>{
      let currentSequence = sequence + 1
      if(currentSequence>=3){
         currentSequence = 0
      }
      dispatch(sequenceAction(currentSequence))
    }

    const changeMusic = tag =>{
      dispatch(changeCurrentSong(tag))
    }
    const handleMusicEnded = ()=>{
      if(sequence===2){
        // 单曲循环
        audioRef.current.currentTime = 0
      }else{
        dispatch(changeCurrentSong(1))
      }
    }
    //  监听滑块
     const sliderChange = useCallback( value => {
       const currentTime = value/100*duration   //ms 设置这个变量目的是，当滑动进度时setCurrentTime(currentTime) 让currentTime实时变化
        setIsChanging(true)
        setProgress(value)
        setCurrentTime(currentTime) 
       },[duration])
    //监听点击滑块后触发的函数
    const sliderAfterChange = useCallback( value => {
      const currentTime = value/100*duration/1000  //根据value，duration设置currentTime的值在赋给 audioRef.current.currentTime   /1000是转化为秒s 
      audioRef.current.currentTime=currentTime
        setIsChanging(false)
        
        //当暂停后，拖动滑块，拖动滑块后自动播放，isPlaying改为false
        if(!isPlaying){
          playMusic()
        }
       },[duration,isPlaying,playMusic])

   
  return (
    <PlaybarWrapper className="sprite_player">
      <div className="content wrap-v2">
          <Control isPlaying={isPlaying}>
            <button className="sprite_player prev" onClick={e=>changeMusic(-1)}></button>
            <button className="sprite_player play" onClick={e=>playMusic()}></button>
            <button className="sprite_player next"  onClick={e=>changeMusic(1)}></button>
          </Control>
          <PlayInfo>
            <div className="image">
              <NavLink to="/discover/player">
              <img src={getSizeImage(picUrl, 34)} alt="" />
            </NavLink>
            </div>
            <div className="info">
              <div className="song">
                <span className="song-name">{songName}</span> 
                 <a className="singer-name" href="/#">{singerName}</a>
              </div>
              <div className="progress">
                <Slider value={progress} onChange={sliderChange}  onAfterChange={sliderAfterChange} />
                <div className="time">
                  <span className="now-time">{showCurrentTime}</span>
                  <span className="divider">/</span>
                  <span className="duration">{showDuration}</span>
                </div>       
              </div>
            </div>
          </PlayInfo>   
          <Operator sequence={sequence}>
          <div className="left">
            <button className="sprite_player btn favor"></button>
            <button className="sprite_player btn share"></button>
          </div>
          <div className="right sprite_player">
            <button className="sprite_player btn volume"></button>
            <button className="sprite_player btn loop" onClick={e => changeSequence()}></button>
            <button className="sprite_player btn playlist"></button>
          </div>
        </Operator>
      </div>
       <audio ref={audioRef} onTimeUpdate={e=>timeUpdate(e)} onEnded={handleMusicEnded}/>
    </PlaybarWrapper>
  )
})
